package com.herohead;

import java.io.StringWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class NWsavegroup {

	public static String savegroupName;
	public static String startTime;
	public static String endTime;
	public static String restartTime;
	public static String[] succeeded;
	public static String[] failed;
	public static String[] disabled;
	public static String groupStatus;
	public static String totalClients;
	public static int succeededCount = 0;
	public static int failedCount = 0;
	public static int disabledCount = 0;
	public static String[] saveGroupLog;
	public static List<String> tolalClientList;
	public static String convertNWDateToTS(String ts) {
		//String ts = "Wed sep 21 02:00:00 2013";
		//Misc m = new Misc();

		String[] tss = ts.split(" ");
		String month = tss[1];
		String dayNum = tss[2];
		String tm = tss[3];
		String yy = tss[4];
		String mts = yy + "-" + Misc.getMonthNumStr(month) + "-" + dayNum + " " + tm;
		Timestamp ts1 = Timestamp.valueOf(mts);
		return ts1.toString();
	}
	public static String getClientListStr () {

		String returnStr = "";
		for (String s : tolalClientList) {
			returnStr = returnStr + " " + s;
		}

		return returnStr.trim();
	}


	public static void getGroupDetails(String[] slist) {

		String s1;
		for (String s : slist)
			if (s.startsWith("NetWorker savegroup:")) {
				String delims1 = "[(]";
				String delims2 = "[)]";
				s1 = s.split(delims1)[1];
				groupStatus = s1.split(delims2)[0];
				savegroupName = s1.split(delims2)[1].split(" ")[1];
				totalClients = s1.split(",")[1].split(" ")[2];
				break;
			}
	}

	public String system;


	public String sourceServer;

	public boolean checkIfExist(String client) {
		Boolean returnValue = false;

		for (String s : tolalClientList )
			if (s.contains(client)) {
				returnValue = true;
				break;
			}
		return returnValue;
	}
	public void createTotalList() {
		//List t;

		List<String> t = new ArrayList<String>();

		if (succeeded != null) {
			for (String s : succeeded)
				t.add(s.trim());
		}
		if (failed != null) {
			for (String s : failed)
				t.add(s.trim());
		}
		if (disabled != null) {
			for (String s : disabled)
				t.add(s.trim());
		}
		tolalClientList = t;
	}
	private String deleteLastChar(String s) {
		return s.substring(0, s.length() -1);
	}
	/*
	 * <savegroupname>
	 * <savegroupstatus>
	 * <savegroupstarttime>
	 * <savegroupendtime>
	 * <savegrouprestarttime>
	 * <savegroupclientCount>
	 * <clientlist>
	 * <client>
	 * <status>
	 * 
	 */
	public String formatXML(String system, String sourceSource,String savegroupName, String savegroupStatus, String savegroupStartTime, String savegroupEndTime, String savegroupRestartTime, String savegroupclientCount,String clientlist,String client, String status, String clientDetails ) throws TransformerException{

		String timeStamp = Misc.getTimestamp();

		try {

			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

			// root elements
			Document doc = docBuilder.newDocument();
			Element rootElement = doc.createElement("savegrouplog");
			doc.appendChild(rootElement);

			Element e0 = doc.createElement("timestamp");
			e0.appendChild(doc.createTextNode(timeStamp));
			rootElement.appendChild(e0);

			Element es = doc.createElement("system");
			es.appendChild(doc.createTextNode(system));
			rootElement.appendChild(es);

			Element es1 = doc.createElement("sourceSource");
			es.appendChild(doc.createTextNode(sourceSource));
			rootElement.appendChild(es1);

			Element e = doc.createElement("savegroupname");
			e.appendChild(doc.createTextNode(savegroupName));
			rootElement.appendChild(e);

			Element e1 = doc.createElement("savegroupStatus");
			e1.appendChild(doc.createTextNode(savegroupStatus));
			rootElement.appendChild(e1);

			Element e2 = doc.createElement("savegroupStartTime");
			e2.appendChild(doc.createTextNode(savegroupStartTime));
			rootElement.appendChild(e2);

			Element e3 = doc.createElement("savegroupEndTime");
			e3.appendChild(doc.createTextNode(savegroupEndTime));
			rootElement.appendChild(e3);

			Element e4 = doc.createElement("savegroupRestartTime");
			e4.appendChild(doc.createTextNode(savegroupRestartTime));
			rootElement.appendChild(e4);

			Element e5 = doc.createElement("savegroupclientCount");
			e5.appendChild(doc.createTextNode(savegroupclientCount));
			rootElement.appendChild(e5);

			Element e6 = doc.createElement("clientlist");
			e6.appendChild(doc.createTextNode(clientlist));
			rootElement.appendChild(e6);

			Element e7 = doc.createElement("client");
			e7.appendChild(doc.createTextNode(client));
			rootElement.appendChild(e7);

			Element e8 = doc.createElement("status");
			e8.appendChild(doc.createTextNode(status));
			rootElement.appendChild(e8);

			Element e9 = doc.createElement("clientdetails");
			e9.appendChild(doc.createTextNode(clientDetails));
			rootElement.appendChild(e9);


			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			//DOMSource source = new DOMSource(doc);

			//StreamResult result = new StreamResult(new String("soutput"));

			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new StringWriter());
			transformer.transform(source, result);
			//System.out.println(result.getWriter().toString());

			return result.getWriter().toString();


		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
			return pce.toString();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.toString();
		}

	}

	public String getBackupType(String[] slist) {

		String backupType = null;
		for (String s : slist)
			if (s.contains("file")) {
				backupType =  s.split("level=")[1].split(" ")[0].split(",")[0];
			}

		if (backupType == null) backupType = "";

		return backupType;
	}

	public List<String> getClientList () {
		return tolalClientList;
	}



	public String getClientStatus(String server) {
		String returnString = "";
		if (succeeded != null) {
			for (String s : succeeded)
				if (s.contains(server)) {
					returnString = "Succeeded";
					break;
				}
		}
		if (failed != null) {
			for (String s : failed)
				if (s.contains(server)) {
					returnString = "Failed";
					break;
				}
		}
		if (disabled != null) {
			for (String s : disabled)
				if (s.contains(server)) {
					returnString = "Disabled";
					break;
				}
		}
		return returnString;
	}

	public String getDetails(String server) {
		String returnString = "";
		for (String s : saveGroupLog) {
			if (s.contains(server)) {
				String sss = (s.substring(2, s.length()));
				if (sss.startsWith(server))
					returnString = returnString + s + "\n";
			}
		}
		return returnString;
	}

	public void getDisabled(String[] slist) {
		String[] returnString = null;
		for (String s : slist)
			if (s.startsWith("Disabled")) {
				returnString = s.split(":")[1].split(", ");
				disabled = returnString;
				disabledCount = disabled.length;
				break;
			}
	}

	public String getDisabledString() {
		return getStringFromList(disabled);
	}

	public void getEndTime(String[] slist) {

		String returnString = "";
		for (String s : slist)
			if (s.startsWith("End time")) {
				returnString = s.split("End time:")[1];
				break;
			}
		endTime = returnString.trim();

	}

	public void getFailed(String[] slist) {
		String[] returnString = null;
		for (String s : slist)
			if (s.startsWith("Failed")) {
				returnString = s.split(":")[1].split(", ");
				failed = returnString;
				failedCount = failed.length;
				break;
			}

	}

	public String getFailedString() {
		return getStringFromList(failed);
	}

	public String getModule(String[] slist) {

		String backupModule = null;
		for (String s : slist)
			if (s.contains("file")) {
				backupModule =  s.split(":")[1];
			}

		if (backupModule == null) backupModule = "";

		return backupModule;
	}

	public String getNumfiles(String[] slist) {

		String numFiles = null;
		for (String s : slist)
			if (s.contains("file")) {
				String s2 = s.split("file")[0];
				String[] s3 = s2.split(" ");
				numFiles = s3[s3.length-1];
			}

		if (numFiles == null) numFiles = "0";

		return numFiles;
	}

	public void getRestartTime(String[] slist) {

		String returnString = "";
		for (String s : slist)
			if (s.startsWith("Restart time:")) {
				returnString = s.split("Restart time:")[1];
				break;
			}
		restartTime = returnString.trim();

	}


	public String getSize(String[] slist) {

		String size = null;
		for (String s : slist)
			if (s.contains("file")) {
				String s2 = s.split(",")[1];
				String[] s3 = s2.trim().split(" ");
				size = s3[0] + " " + s3[1];
			}

		if (size == null) size = "0";

		return size;
	}

	public void getStartTime(String[] slist) {

		String returnString = "";
		for (String s : slist)
			if (s.startsWith("Start time")) {
				returnString = s.split("Start time:")[1];
				break;
			}
		startTime = returnString.trim();

	}

	private String getStringFromList(String[] slist){
		String ss = "";
		if (slist == null) return "";
		for (String s : slist)
			ss = ss + s.trim() + ",";
		ss = deleteLastChar(ss);
		return ss;
	}

	public void getSucceeded(String[] slist) {
		String[] returnString = null;
		for (String s : slist)
			if (s.startsWith("Succeeded")) {
				returnString = s.split(":")[1].split(", ");
				succeeded = returnString;
				succeededCount = succeeded.length;
				break;
			}

	}

	public String getSucceededString() {
		return getStringFromList(succeeded);
	}

	public void loadVars(String[] slist){
		saveGroupLog = slist;
		getStartTime(slist);
		getSucceeded(slist);
		getFailed(slist);
		getDisabled(slist);
		getEndTime(slist);
		getGroupDetails(slist);
		getRestartTime(slist);
		createTotalList();

	}

}